package grandehealth.kurentoandroidonetoone;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.media.AudioManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.webrtc.EglBase;
import org.webrtc.MediaStream;
import org.webrtc.SurfaceViewRenderer;
import org.webrtc.VideoRenderer;

import grandehealth.AudioVideoSDK.WebRTC.RegisterNameCommand;
import grandehealth.AudioVideoSDK.WebRTC.RejectCallCommand;
import grandehealth.AudioVideoSDK.WebRTC.RtcListener;
import grandehealth.AudioVideoSDK.WebRTC.WebRtcClient;
import grandehealth.AudioVideoSDK.WebRTCPeer.NBMMediaConfiguration;

import static grandehealth.AudioVideoSDK.WebRTC.WebRtcClient.CallTypeForAudio;
import static grandehealth.AudioVideoSDK.WebRTC.WebRtcClient.CallTypeForAudioVideo;
import static grandehealth.AudioVideoSDK.WebRTC.WebRtcClient.CallTypeForNone;

public class MainActivity extends AppCompatActivity implements RtcListener {

    private static final String TAG = MainActivity.class.getSimpleName();
    private static final int CAMERA_MIC_PERMISSION_REQUEST_CODE = 1;


    private WebRtcClient rtcClient;

    //  切换音频、摄像头等
    private int currVolume = 0;


    public static final int CAMERA_WIDTH = 320;
    public static final int CAMERA_HEIGHT = 240;


    //  SurfaceViewRenderer -- 01-09
    private EglBase rootEglBase;
    SurfaceViewRenderer viewRenderLocal;    // 本地 渲染视图
    SurfaceViewRenderer viewRenderRemote;   // 远端 渲染视图

    private String getUserNameIsLocal;      //  本地自己的名字
    private String getUserNameIsOther;      //  其他人的名字

    private boolean isFront = false;


    private Button  btn_register;           //  注册本地用户名

    private Button  btn_call_AudioVideo;    //  呼叫音视频
    private Button  btn_call_Audio;         //  呼叫音频
    private Button  btn_stop_call;          //  停止呼叫

    private Button  btn_change_speaker;     //  扩音
    private Button  btn_change_camera;      //  切换摄像头
    private Button  btn_close_local_camera; //  关闭本地摄像头

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 需要申请权限
        requestPermissionForCameraAndMicrophone();

        //  SurfaceViewRenderer -- 01-09
        rootEglBase = EglBase.create();

        setBtnViewById();

        viewRenderLocal.init(rootEglBase.getEglBaseContext(), null);
        viewRenderRemote.init(rootEglBase.getEglBaseContext(), null);

        viewRenderLocal.setZOrderMediaOverlay(true);

        // 连接 通信服务器
        onWebRtcClient();

    }

    private void setBtnViewById(){

        viewRenderLocal  = (SurfaceViewRenderer)findViewById(R.id.video_view_local);
        viewRenderRemote = (SurfaceViewRenderer)findViewById(R.id.video_view_remote);

        //  注册
        btn_register = (Button)findViewById(R.id.btn_register );

        //  呼叫音视频
        btn_call_AudioVideo = (Button)findViewById(R.id.btn_call_AudioVideo );
        //  呼叫音频
        btn_call_Audio = (Button)findViewById(R.id.btn_call_Audio );
        //  停止呼叫
        btn_stop_call = (Button)findViewById(R.id.btn_stop_call );

        //  扩音
        btn_change_speaker = (Button)findViewById(R.id.btn_change_speaker );
        //  切换摄像头
        btn_change_camera = (Button)findViewById(R.id.btn_change_camera );
        //  关闭本地摄像头
        btn_close_local_camera = (Button)findViewById(R.id.btn_close_local_camera );
    }

    @Override
    protected void onResume() {
        super.onResume();
        isFront=true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        isFront=false;
    }

    private void onWebRtcClient() {
        // 连接 通信服务器

        Point displaySize = new Point();
        getWindowManager().getDefaultDisplay().getSize(displaySize);

        String getKurentoUrl = "wss://app86.fromfuture.cn:9999/call";
//        String getKurentoUrl = "wss://app141.fromfuture.cn:9999/call";

        rtcClient = new WebRtcClient( MainActivity.this, MainActivity.this, getKurentoUrl, CAMERA_WIDTH, CAMERA_HEIGHT, rootEglBase.getEglBaseContext(), viewRenderLocal, viewRenderRemote );

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onSocketCompleted() {
        // socket 连接成功

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText( MainActivity.this, "网络连接成功", Toast.LENGTH_SHORT).show();

                //   注册
                if ( !btn_register.isEnabled() ){
                    btn_register.setEnabled(true);
                }
            }
        });
    }

    public void clickRegister(View view){
        // 注册 用户名

        TextView getTextViewLocal = (TextView) findViewById(R.id.user_name_local );
        getUserNameIsLocal = getTextViewLocal.getText().toString();

        if ( getUserNameIsLocal.length() == 0 ){
            System.out.println("getUserNameIsLocal : " + getUserNameIsLocal );
            Toast.makeText( MainActivity.this, "本地的用户名不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        rtcClient.sendMessage(new RegisterNameCommand("gz", "gz", getUserNameIsLocal));
        rtcClient.webRTCApp.setConnectionId( getUserNameIsLocal );
    }

    @Override
    public  void onRegisterSuccessed() {
        // 注册用户名成功
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText( MainActivity.this, "用户 " + getUserNameIsLocal + " 注册成功", Toast.LENGTH_SHORT).show();
                // 设置 按钮初始化 状态
                setBtnInitStatus();
            }
        });
    }

    @Override
    public void onRegisterFailed() {
        // 注册用户名失败后
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText( MainActivity.this, "用户 " + getUserNameIsLocal + " 注册失败", Toast.LENGTH_SHORT).show();
                //  呼叫音视频
                btn_call_AudioVideo.setEnabled(false);
                //  呼叫音频
                btn_call_Audio.setEnabled(false);
            }
        });
    }


    @Override
    public  void onCallResponseFailed(String alertMsg) {
        // 呼叫 响应 失败
        final String getAlertMsg = alertMsg;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                AlertDialog.Builder builder = new AlertDialog.Builder( MainActivity.this );
                builder.setMessage( getAlertMsg ).setPositiveButton(" 确定 ",  null ).show();

                // 停止 视频流 播放
                rtcClient.stopCommunication();
            }
        });
    }

    private void setBtnInitStatus(){
        // 设置 按钮初始化 状态
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    //  呼叫音视频
                    if ( !btn_call_AudioVideo.isEnabled() ){
                        btn_call_AudioVideo.setEnabled(true);
                    }
                    //  呼叫音频
                    if ( !btn_call_Audio.isEnabled() ){
                        btn_call_Audio.setEnabled(true);
                    }
                    //  停止呼叫
                    if ( btn_stop_call.isEnabled() ) {
                        btn_stop_call.setEnabled(false);
                    }

                    //  扩音
                    if ( btn_change_speaker.isEnabled() ) {
                        btn_change_speaker.setEnabled(false);
                    }
                    //  切换摄像头
                    if ( btn_change_camera.isEnabled() ) {
                        btn_change_camera.setEnabled(false);
                    }
                    //  关闭本地摄像头
                    if ( btn_close_local_camera.isEnabled() ) {
                        btn_close_local_camera.setEnabled(false);
                    }
                } catch (Exception e) {
                    Log.d( "Exception : ", e + "" );

                }
            }
        });
    }

    @Override
    public void onSetBtnCallAudioVideoStatus(){
        // 设置 按钮 -- 呼叫音视频的 状态

        //  呼叫音视频
        if ( btn_call_AudioVideo.isEnabled() ){
            btn_call_AudioVideo.setEnabled(false);
        }
        //  呼叫音频
        if ( btn_call_Audio.isEnabled() ){
            btn_call_Audio.setEnabled(false);
        }
        //  停止呼叫
        if ( !btn_stop_call.isEnabled() ) {
            btn_stop_call.setEnabled(true);
        }

        //  扩音
        if ( !btn_change_speaker.isEnabled() ) {
            btn_change_speaker.setEnabled(true);
        }
        //  切换摄像头
        if ( !btn_change_camera.isEnabled() ) {
            btn_change_camera.setEnabled(true);
        }
        //  关闭本地摄像头
        if ( !btn_close_local_camera.isEnabled() ) {
            btn_close_local_camera.setEnabled(true);
        }
    }

    @Override
    public void onSetBtnCallAudioStatus(){
        // 设置 按钮 -- 呼叫音频的 状态

        //  呼叫音视频
        if ( btn_call_AudioVideo.isEnabled() ){
            btn_call_AudioVideo.setEnabled(false);
        }
        //  呼叫音频
        if ( btn_call_Audio.isEnabled() ){
            btn_call_Audio.setEnabled(false);
        }
        //  停止呼叫
        if ( !btn_stop_call.isEnabled() ) {
            btn_stop_call.setEnabled(true);
        }

        //  扩音
        if ( !btn_change_speaker.isEnabled() ) {
            btn_change_speaker.setEnabled(true);
        }
        //  切换摄像头
        if ( btn_change_camera.isEnabled() ) {
            btn_change_camera.setEnabled(false);
        }
        //  关闭本地摄像头
        if ( btn_close_local_camera.isEnabled() ) {
            btn_close_local_camera.setEnabled(false);
        }

        // 隐藏 视频视图
        onVideoViewHiddenOrShow( true, false );
        onVideoViewHiddenOrShow( false, false );

    }



    @Override
    public void onCallReceived(final String from) {
        // 得到 -- 其他人的呼叫
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which){
                            case DialogInterface.BUTTON_POSITIVE:
                                // 同意 接听通信
                                rtcClient.acceptCall();
                                break;

                            case DialogInterface.BUTTON_NEGATIVE:
                                // No button clicked -- 拒绝
                                rtcClient.sendMessage(new RejectCallCommand(null, RejectCallCommand.USER_REJECT));
                                break;
                        }
                    }
                };

                if ( isFront ){
                    String getAlertTitle = "用户 " + from + " 邀请您";
                    if ( rtcClient.getGetCallType() == CallTypeForAudioVideo ){
                        getAlertTitle = getAlertTitle + " 音视频通话 \n 是否接受？";
                    }else if ( rtcClient.getGetCallType() == CallTypeForAudio ){
                        getAlertTitle = getAlertTitle + " 音视频通话 \n 是否接受？";
                    }

                    AlertDialog.Builder builder = new AlertDialog.Builder( MainActivity.this );
                    builder.setMessage( getAlertTitle ).setPositiveButton("是", dialogClickListener)
                            .setNegativeButton("否", dialogClickListener).show();
                }else {
                    System.out.println("不在前台");

                    // 发送 拒绝通信 的信令
                    rtcClient.sendMessage(new RejectCallCommand(null, RejectCallCommand.USER_REJECT));
                }

            }
        });

        rtcClient.currentFrom = from;
        rtcClient.webRTCApp.setFromUserId(from);
    }



    public void clickCallAudioVideo(View view){
        // 呼叫 音视频
        rtcClient.setGetCallType( CallTypeForAudioVideo );

        // 开始 呼叫其他人
        startCallOtherUser();
    }

    public void clickCallAudio(View view){
        // 呼叫 音频  -- 语音通信
        rtcClient.setGetCallType( CallTypeForAudio );

        // 开始 呼叫其他人
        startCallOtherUser();

    }

    private void startCallOtherUser(){
        // 开始 呼叫其他人
        TextView getTextViewOther = (TextView) findViewById(R.id.user_name_other );
        getUserNameIsOther = getTextViewOther.getText().toString();

        if ( getUserNameIsOther.length() == 0 ){
            rtcClient.setGetCallType( CallTypeForNone );
            System.out.println("getUserNameIsOther : " + getUserNameIsLocal );
            Toast.makeText( MainActivity.this, "呼叫方的用户名不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // 执行 呼叫其他人

                if ( rtcClient.getGetCallType() == CallTypeForAudio ){
                    // 设置 按钮 -- 呼叫音频的 状态
                    onSetBtnCallAudioStatus();

                }else if (rtcClient.getGetCallType() == CallTypeForAudioVideo ){
                    // 设置 按钮 -- 呼叫音视频的 状态
                    onSetBtnCallAudioVideoStatus();

                }

                rtcClient.callOtherUser( getUserNameIsOther );
            }
        });
    }



    private void requestPermissionForCameraAndMicrophone(){
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) ==
                PackageManager.PERMISSION_GRANTED){
        }else{
            // 需要申请权限
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA}, 1 );
        }
    }
    private void audiopermission(){
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) ==
                PackageManager.PERMISSION_GRANTED){
            audiopermission();
        }else{
            //需要申请权限
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.RECORD_AUDIO},2);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case 1: {//相机权限
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    audiopermission();
                } else {
                    audiopermission();
                }
                return;
            }
            case 2:

        }
    }

    public void clickChangeSpeaker(View view){
        // 切换音频播放方式
        Button btnView = (Button)view;
        if ( btnView.getText().equals("扩音") ){
            // 从听筒 转为 扬声器
            try{
                AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                audioManager.setMode(AudioManager.ROUTE_SPEAKER);
                currVolume = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
                if(!audioManager.isSpeakerphoneOn()) {
                    //setSpeakerphoneOn() only work when audio mode set to MODE_IN_CALL.
                    audioManager.setMode(AudioManager.MODE_IN_CALL);
                    audioManager.setSpeakerphoneOn(true);
                    audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
                            audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL ),  AudioManager.STREAM_VOICE_CALL);
                }
                btnView.setText("听筒");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if ( btnView.getText().equals("听筒") ){
            // 从 扬声器 转为 听筒
            try {
                AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                if(audioManager != null) {
                    if(audioManager.isSpeakerphoneOn()) {
                        audioManager.setSpeakerphoneOn(false);
                        audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,currVolume, AudioManager.STREAM_VOICE_CALL );
                    }
                }
                btnView.setText("扩音");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void clickChangeCamera(View view){
        // 切换摄像头
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                rtcClient.switchCamera();
            }
        });
    }

    public void clickCloseLocalCamera(View view){
        // 音视频通信，关闭 或 打开 本地摄像头

        // 本地摄像头 -- 关闭 或 打开
        rtcClient.setLocalCameraIsCloseOrOpen();

        Button btnView = (Button)view;
        if ( btnView.getText().equals("关闭本地摄像头") ){
            // 关闭本地摄像头 转为 打开本地摄像头
            btnView.setText("打开本地摄像头");
        }else if ( btnView.getText().equals("打开本地摄像头") ){
            // 打开本地摄像头 转为 关闭本地摄像头
            btnView.setText("关闭本地摄像头");
        }
    }

    @Override
    public void onVideoViewHiddenOrShow( Boolean isLocalVideo, Boolean isShow){
        // 本地 或 远端的 视频视图 隐藏或显示
        final Boolean getIsLocalVideo = isLocalVideo;
        final Boolean getIsShow = isShow;

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    if ( getIsLocalVideo ){
                        // 本地 视频视图
                        if ( getIsShow ){
                            viewRenderLocal.setVisibility( View.VISIBLE );
                        }else{
                            viewRenderLocal.setVisibility( View.INVISIBLE );
                        }
                    }else{
                        // 远端 视频视图
                        if ( getIsShow ){
                            viewRenderRemote.setVisibility( View.VISIBLE );
                        }else{
                            viewRenderRemote.setVisibility( View.INVISIBLE );
                        }
                    }
                } catch (Exception e) {
                    Log.d( " e.printStackTrace() : ",  e + "" );

                }
            }
        });
    }


    public void clickStopCall(View view){
        // 停止 音视频 或 音频

        // 发送 停止呼叫的信令
        rtcClient.sendStopCallAV();

    }


    @Override
    public void onStopAVPlayView() {
        // 停止 音视频 播放的 视图

        // 设置 按钮初始化 状态
        setBtnInitStatus();


        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                // 移除 视频视图的画面
//                viewRenderLocal.release();
//                viewRenderRemote.release();

//                viewRenderLocal.setZOrderMediaOverlay( true );
//                viewRenderRemote.setZOrderMediaOverlay( true );

//                viewRenderLocal.setZOrderOnTop( true );
//                viewRenderRemote.setZOrderOnTop( true );

            }
        });
    }

}
